package cc.co.cutenimy.nimyexplore.rcp;

import java.beans.PropertyChangeSupport;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.core.runtime.Assert;

import cc.co.cutenimy.nimyexplore.model.connection.ConnectionOptions;
import cc.co.cutenimy.nimyexplore.model.jdbc.ConnectionInstance;
import cc.co.cutenimy.nimyexplore.model.util.ConnectionOptionsGenerator;

public class ApplicationContext extends PropertyChangeSupport {

	public static final String CONNECTION_INSTANCE_ADDED = "CONNECTION_INSTANCE_ADDED";
	public static final String CONNECTION_INSTANCE_REMOVED = "CONNECTION_INSTANCE_REMOVED";
	public static final String OPTION_FILE_PATH = "options";

	private static final long serialVersionUID = -7996752120677278777L;
	private static ApplicationContext INS;
	private final ConnectionOptionsGenerator generator;
	private final List<ConnectionInstance> connectionOptionsInstances;

	private ApplicationContext() {
		super("");
		generator = new ConnectionOptionsGenerator();
		connectionOptionsInstances = new ArrayList<ConnectionInstance>(20);
	}

	public static ApplicationContext get() {
		if (INS == null) {
			INS = new ApplicationContext();
		}
		return INS;
	}

	/**
	 * TODO
	 * 
	 * @return
	 */
	public List<ConnectionOptions> loadConnectionOptions() {
		return generator.loadFrom(getOptionsStorePath());
	}

	public ConnectionInstance from(final ConnectionOptions options) {
		Assert.isNotNull(options);
		return generator.assemble(options);
	}

	public List<ConnectionInstance> add(final ConnectionInstance instance) {
		Assert.isNotNull(instance);
		if (!connectionOptionsInstances.contains(instance)) {
			connectionOptionsInstances.add(instance);
			firePropertyChange(CONNECTION_INSTANCE_ADDED, null, instance);
		}
		return Collections.unmodifiableList(connectionOptionsInstances);
	}

	public List<ConnectionInstance> remove(final ConnectionInstance instance) {
		Assert.isNotNull(instance);
		if (connectionOptionsInstances.contains(instance)) {
			connectionOptionsInstances.remove(instance);
			firePropertyChange(CONNECTION_INSTANCE_REMOVED, instance, null);
		}
		return Collections.unmodifiableList(connectionOptionsInstances);
	}

	public List<ConnectionInstance> listConnectionInstances() {
		return Collections.unmodifiableList(connectionOptionsInstances);
	}

	private String getOptionsStorePath() {
		File file = new File(OPTION_FILE_PATH);
		if (file.exists() && file.isDirectory()) {
			return file.getAbsolutePath();
		} else {
			if (!file.exists()) {
				file.delete();
			}
			file.mkdir();
			return file.getAbsolutePath();
		}
	}
}
